import { mongo } from '#nuxt-mongodb';

interface UserSubmit {
    name:string,
    account:string,
    password:string
}

export default defineEventHandler(async (event:any)=>{
    // console.log(event.body)
    /*const {name,accout,password} = await readBody(event);
    // console.log(body)
    return {
        status:200,
        data:{
            name: name,
            accout:accout,
            password:password
        }
    }*/
    try {
        const {name,account,password}:UserSubmit = await readBody(event);
        console.log(name,account,password)
        // const userData = JSON.parse(body)
        const users = mongo.db().collection('user')
        // 插入数据前，确保所有字段都不应为null
        const result = await users.insertOne({
            name:name ?? '',
            account:account ?? '',
            password:password ?? ''})
        return {
            status: 200,
            message: 'User added successfully'
            }
    }catch(err:any){
        return {
            status: 500,
            body: JSON.stringify({
              message: 'Failed to add user',
              error: err.message
            })
          }
    }
 })